#include "choosefrienddialog.h"
#include"debug.h"
#include"model/data.h"
#include"./model/datacenter.h"
#include"./toast.h"

#include<QScrollArea>
#include<QScrollBar>
#include<QHBoxLayout>
#include<QCheckBox>
#include<QPushButton>
#include<QList>
#include<QPainter>

//////////////////////////////////////////////////
////// 选择好友窗口的一个元素/好友项
//////////////////////////////////////////////////
ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog* owner,const QString& userId, const QIcon &avatar, const QString &name, bool checked)
    :userId(userId)
{
    //1.设置控件的基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //2.设置布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20,0,20,0);
    this->setLayout(layout);

    //3.创建复选框
    checkBox = new QCheckBox();
    checkBox->setChecked(checked);
    checkBox->setFixedSize(25,25);
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 20px; height: 20px; image: url(:/resource/image/unchecked.png);}";
    style += "QCheckBox::indicator:checked { image: url(:/resource/image/checked.png);}";
    checkBox->setStyleSheet(style);

    //4.创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40,40);
    avatarBtn->setIconSize(QSize(40,40));
    avatarBtn->setIcon(avatar);

    //5.创建名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel { background-color: transparent;}");

    //6.添加上述内容到布局管理器中
    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);

    //7.连接信号槽
    connect(checkBox,&QCheckBox::toggled,this,[=](bool checked){
        if(checked){
            //勾选了复选框，把当前这个Item，添加到右侧的已选择区域
            owner->addSelectedFriend(userId,avatar,name);
        }
        else{
            //取消勾选
            //LOG() << "运行到这里";
            owner->deleteSelectedFriend(userId);
        }
    });

}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void)event;

    //根据鼠标的进入状态，来决定绘制成不同的颜色
    QPainter painter(this);
    if(isHover){
        //绘制成深色
        painter.fillRect(this->rect(),QColor(230,230,230));
    }
    else{
        //绘制成浅色
        painter.fillRect(this->rect(),QColor(255,255,255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void)event;
    isHover = true;
    //update 相当于"更新界面"
    this->update();
    //或者使用下列代码
    //this->repaint();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void)event;
    isHover = false;
    this->update();
}


ChooseFriendDialog::ChooseFriendDialog(QWidget *parent,const QString& userId)
    :QDialog(parent),userId(userId)
{
    //1.设置窗口的基本属性
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setFixedSize(750,550);
    this->setStyleSheet("QDialog { background-color: rgb(255,255,255);}");

    //2.创建布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setContentsMargins(20,0,20,20);
    layout->setSpacing(10);
    this->setLayout(layout);

    //3.针对左侧窗口进行初始化
    initLeft(layout);

    //4.针对右侧窗口进行初始化
    initRight(layout);

    initData();
}

void ChooseFriendDialog::initLeft(QHBoxLayout *layout)
{
    //1.创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255,255,255);}");
    scrollArea->setStyleSheet("QScrollArea { border:none;}");
    layout->addWidget(scrollArea,1);

    //2.创建QWidget设置到滚动区域中
    totalContainer = new QWidget();
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer { background-color: rgb(255,255,255);}");
    scrollArea->setWidget(totalContainer);

    //3.创建左侧窗口内部的垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    totalContainer->setLayout(vlayout);

    //4.进一步添加vlayout内部的元素
#if TEST_UI
    QIcon defaultAvatar(":/resource/image/defaultAvatar.png");
    for(int i = 0;i < 30;i++){
        this->addFriend(QString::number(1000 + i),defaultAvatar,"张三" + QString::number(i),false);
    }
#endif
}

void ChooseFriendDialog::initRight(QHBoxLayout *layout)
{
    //1.创建右侧的布局管理器
    QGridLayout* gridlayout = new QGridLayout();
    gridlayout->setContentsMargins(0,0,0,0);
    gridlayout->setSpacing(0);
    layout->addLayout(gridlayout,1);

    //2.创建"提示"label
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700}");

    //3.创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255,255,255);}");
    scrollArea->setStyleSheet("QScrollArea {border: none;}");
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    //4.创建滚动区域中的QWidget
    selectContainer = new QWidget();
    selectContainer->setObjectName("selectContainer");
    selectContainer->setStyleSheet("#selectContainer { background-color: rgb(255,255,255);}");
    scrollArea->setWidget(selectContainer);

    //5.创建selectContainer中的"垂直布局";
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0,0,0,0);
    vlayout->setAlignment(Qt::AlignTop);
    selectContainer->setLayout(vlayout);

    //6.创建底部按钮
    QString style = "QPushButton { color: rgb(7,191,96); background-color: rgb(240,240,240);border: none;border-radius:5px;}";
    style += "QPushButton:hover { background-color: rgb(220,220,220);} QPushButton:pressed { background-color: rgb(200,200,200);}";

    QPushButton* okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(style);

    QPushButton* cancelBtn = new QPushButton();
    cancelBtn->setFixedHeight(40);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);

    //7.把上述控件添加到布局中
    gridlayout->addWidget(tipLabel,0,0,1,9);
    gridlayout->addWidget(scrollArea,1,0,1,9);
    gridlayout->addWidget(okBtn,2,1,1,3);
    gridlayout->addWidget(cancelBtn,2,5,1,3);


    //构造一些数据用来测试界面
#if 0
    //此处的数据通过勾选左侧列表生成
    QIcon defaultAvatar(":/resource/image/defaultAvatar.png");
    for(int i = 0;i < 30;i++){
        this->addSelectedFriend(QString::number(1000+i),defaultAvatar,"张三" + QString::number(i));
    }
#endif

    //8.添加信号槽,处理ok和cancel的点击
    connect(okBtn,&QPushButton::clicked,this,&ChooseFriendDialog::clickOkBtn);
    connect(cancelBtn,&QPushButton::clicked,this,[=](){
        this->close();
    });

}

void ChooseFriendDialog::initData()
{
   //遍历好友列表，把好友列表中的所有元素,添加到这个窗口界面上
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    QList<model::UserInfo>* friendList = dataCenter->getFriendList();
    if(friendList == nullptr){
        LOG() << "加载数据是发现好友列表为空!";
        return ;
    }
    for(auto it = friendList->begin();it != friendList->end();it++){
        if(it->userId == userId){
            this->addSelectedFriend(it->userId,it->avatar,it->nickname);
            this->addFriend(it->userId,it->avatar,it->nickname,true);
        }else{
            this->addFriend(it->userId,it->avatar,it->nickname,false);
        }
    }

}

void ChooseFriendDialog::clickOkBtn()
{
    //1.根据选中的好友列表中的元素，得到所有的要创建群聊会话的用户id列表
    QList<QString> userList = generateMemberList();
    if(userList.size() < 3){
        Toast::showMessage("群聊中的成员不足三个，无法创建群聊");
        return ;
    }

    //2.发送网络请求创建群聊
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->createGroupChatSessionAsync(userList);

    //3.关闭窗口
    this->close();
}

QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> result;

    //1.把自己添加到结果中
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    if(dataCenter->getMyself() == nullptr){
        LOG() << "个人信息尚未加载!";
        return result;
    }
    result.push_back(dataCenter->getMyself()->userId);

    //2.遍历选中的列表
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectContainer->layout());
    for(int i = 0;i < layout->count();++i){
        auto* item = layout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr){
            continue;
        }
        auto* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        result.push_back(chooseFriendItem->getUserId());
    }
    return result;
}


void ChooseFriendDialog::addFriend(const QString& userId, const QIcon &avatar, const QString &name, bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,checked);
    totalContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString& userId,const QIcon &avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,true);
    selectContainer->layout()->addWidget(item);
}

void ChooseFriendDialog::deleteSelectedFriend(const QString &userId)
{
    //LOG() << "运行到这里";
    //遍历selectedContainer中的每个Item,对比Item里的userId,找到要删除的的userId
    QVBoxLayout* vlayoutRight = dynamic_cast<QVBoxLayout*>(selectContainer->layout());
    //由于是"遍历"+"删除"需要从后往前进行
    for(int i = vlayoutRight->count() - 1;i >= 0;--i){
        auto* item = vlayoutRight->itemAt(i);
        //LOG() << (item->widget() == nullptr);
        if(item == nullptr || item->widget() == nullptr){
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        //判定当前的Item的userId是否要删除的userId
        if(chooseFriendItem->getUserId() != userId){
            //LOG() << chooseFriendItem->getUserId();
            continue;
        }
        vlayoutRight->removeWidget(chooseFriendItem);
        //此处如果是右侧区域点击复选框取消，那么checkBox是该Item一部分，connect还有要处理的动作
        //手动delete直接删除会报错，需要使用提供的deleteLater，让Qt自己判断何时删除
        chooseFriendItem->deleteLater();
        //LOG() << "运行到这里";
    }
    //LOG() << vlayoutRight->count() - 1;

    //再遍历一下左侧列表，把左侧列表中对应item的checkBox勾选状态取消掉
    QVBoxLayout* vlayoutLeft = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    for(int i = 0;i < vlayoutLeft->count();++i){
        auto* item = vlayoutLeft->itemAt(i);
        if(item == nullptr || item->widget() == nullptr){
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if(chooseFriendItem->getUserId() != userId){
            continue;
        }
        //取消选中状态
        chooseFriendItem->getCheckBox()->setChecked(false);
    }
}


